package com.hoki.zj.hrm.exception;

import com.hoki.zj.hrm.utils.AjaxResult;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = GlobalException.class) // 捕获自定义异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult globalExceptionHandler(GlobalException e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(value = AccessDeniedException.class) // 捕获AccessDeniedException异常
    public AjaxResult accessDeniedHandler(AccessDeniedException e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("不允许访问!!!");
    }

    @ExceptionHandler(value = Exception.class) // 捕获系统异常
    public AjaxResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("操作失败,系统异常!!!");
    }

    // 捕获原生Assert工具抛出的异常
    /*@ExceptionHandler(value = IllegalArgumentException.class)
    public AjaxResult exceptionHandler(IllegalArgumentException e) {
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }*/

    /**
     * 捕获jsr303异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class) // 捕获异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult jsr303ExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        // 获取所欲错误
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();

       /* StringBuilder sb = new StringBuilder();
        // 循环拼接错误
        allErrors.forEach(error -> sb.append(error.getDefaultMessage()).append(","));
        return AjaxResult.me().setSuccess(false).setMessage(sb.toString());*/
        return AjaxResult.me().setSuccess(false).setResultObj
                (allErrors.stream().
                map(DefaultMessageSourceResolvable :: getDefaultMessage)
                .collect(Collectors.joining(",")));
    }
}
